$(function() {
    window.Util = {
        format:function(date) {
            var d = new Date(date),
                r = '';
            var f = function(p) {
                return p<10? "0"+p : p;
            }
            r += d.getFullYear() + '-';
            r += f(d.getMonth()+1) + '-';
            r += f(d.getDate()) + ' ';
            r += f(d.getHours())+ ':';
            r += f(d.getMinutes());
            return r;
        },

        event:{
            tap : ('ontouchstart' in window) ? 'tap' : ((window.DocumentTouch && document instanceof DocumentTouch) ? 'tap' : 'click')
        }
    }

    var app = function() {
        this.name = 'bottles';

        this.el = {
            'page': $("#page"),
            'btnThrow': $("#btnThrow"),
            'btnGet': $("#btnGet"),
            'btnBottle': $("#btnBottle"),
            'btnLogin': $("#btnLogin"),
            'loginPanel': $("#loginPanel"),
            'salvageAnim': $("#salvageAnim"),
            'result': $("#result"),
            'btnSubmitLogin':$("#btnSubmitLogin"),
            'writeBottle' : $("#writeBottle"),
            'btnSubBottleMsg' : $("#btnSubBottleMsg"),
            'bottleMsg' : $("#bottleMsg")
        }
        this.tpls = {
            'bottle': $("#tpl_bottle").html(),
            'bottleList' : $("#tpl_bottleList").html(),
            'msg' : $("#tpl_msg").html(),
            'playerInfo' : $("#tpl_playerInfo").html()
        }

        var href = window.location.href;

        this.url = {
            'autoLogin' : href+'/api.php',
            'requestInfo' : href + '/api.php',
            'login': href + '/api.php',
            'getBottle': href + '/api.php',
            'requestList' : href + '/api.php',
            'requestBottle' : href + '/api.php',
            'sendMsg' : href + '/api.php',
            'throwBottle' : href + '/api.php'
        }

        this.config = {
            showResult: 2500 // 捕捞动作显示时长
        }

        this.user = {};

        this.init();

        this.TEST();
    }

    app.prototype = {

        init: function() {
            this.autoLogin();
            this.initEvent();
        },

        autoLogin:function() {
            var sid = localStorage.getItem('sid');
            var me = this;
            if (sid) {
                $.post(this.url.autoLogin,{
                    method : 'autoLogin',
                    sid : sid
                },function(data) {
                    data = JSON.parse(data);
                    if (data.result) {
                        me.doLoginSuccess.call(me,data)
                    }else{
                        me.initData.call(me);
                    }   
                })
            }else{
                this.initData();
            }
        },

        initData: function() {
            var lastLogin = localStorage.getItem('lastLogin');
            var count_get = 225,
                count_throw = 0;

            if (lastLogin) {
                var lastDate = new Date(parseInt(lastLogin)),
                    currentDate = new Date();
                var last = {
                    year: lastDate.getFullYear(),
                    mon: lastDate.getMonth(),
                    day: lastDate.getDate()
                }
                var now = {
                    year: currentDate.getFullYear(),
                    mon: currentDate.getMonth(),
                    day: currentDate.getDate()
                }
                if (now.year > last.year) {
                    count_get = 5;
                } else if (now.year == last.year && now.mon > last.mon) {
                    count_get = 5;
                } else if (now.year == last.year && now.mon == last.mon && now.day > last.day) {
                    count_get = 5;
                } else {
                    count_get = localStorage.getItem('count_get') || 5;
                }
            }
            
            this.setCount('g',count_get);
            this.setCount('t',count_throw);
            localStorage.setItem('lastLogin', Date.now());
        },

        setCount:function(type,count) {
            if (type == 'g') {
                this.count_get = count;
                this.el.btnGet.find('em').html(count);
                localStorage.setItem('count_get', count);
            }else{
                this.count_throw = count;
                this.el.btnThrow.find('em').html(count);
                localStorage.setItem('count_throw', count);
            }
        },

        initEvent: function() {
            var me = this,
                tap = Util.event.tap;

            // 丢瓶子
            this.el.btnThrow.on(tap, function() {
                console.log('throw bottles');
                if (!me.user.id) {
                    alert('请先登录')
                }
                if (me.count_throw<1) {
                    alert('您今天的机会用完了')
                }else{
                    me.el.writeBottle.show();
                }
            });

            // 丢瓶子btn
            this.el.btnSubBottleMsg.on(tap,function() {
                var msg = $.trim( $("#bottleMsg").val() );
                if (msg) {
                    me.el.writeBottle.find('.notice').hide();
                    $.post(me.url.throwBottle,{
                        method : 'throwBottle',
                        id : me.user.id,
                        msg : msg
                    },function(data) {
                        data = JSON.parse(data);
                        if (data.result) {
                            me.setCount('t',data.count_throw);
                            $("#bottleMsg").val('')
                            me.el.writeBottle.hide();
                            alert('您的瓶子已经丢到海中了~')
                        }
                    })
                }else{
                    me.el.writeBottle.find('.notice').show();
                }
            });

            // 捡一个
            this.el.btnGet.on(tap, function() {
                var status = $(this).data('status');
                if (status != 'anim') {
                    // checkout
                    if (me.count_get < 1) {
                        // TODO
                        alert('您今天捡瓶子机会用完了')
                    } else {
                        $(this).data('status', 'anim');
                        me.el.salvageAnim.addClass('animate').show();
                        me.getBottle.call(me);
                    }
                }
            });

            // 我的瓶子
            this.el.btnBottle.on(tap, function() {
                console.log('check my bottles');
                me.requestList.call(me);
            });

            // 登录 || 显示用户信息
            this.el.btnLogin.on(tap, function() {
                var hasLogin = $(this).hasClass("logined");
                if (hasLogin && me.user) {
                    me.showPlayerInfo.call(me);
                } else {
                    me.showLoginPanel.call(me);
                }
            });

            this.el.btnSubmitLogin.on(tap,function() {
                me.doLogin.call(me);
            });

            // 切换登陆注册页面
            this.el.loginPanel.on(tap, 'label', function() {
                var type = $(this).data('type');
                me.setLoginPanel.call(me, type);
            });

            // 关闭panel
            this.el.page.on(tap, '.btnClose', function() {
                console.log('close panel');
                $(this).parent('.panel').hide();
            });

            /*
                捡瓶子 result
            */

            // 关闭result
            this.el.result.on(tap, '.btnClose', function() {
                me.el.result.hide();
            });

            // 打开看看
            this.el.result.on(tap, '#btnOpen', function() {
                me.el.result.hide();
                me.showBottle.call(me,me.newBottle);
            });

            // 继续捡
            this.el.result.on(tap, '#btnTry', function() {
                me.el.btnGet.trigger(tap);
                me.el.result.hide();
            });

            //  回复瓶子
            this.el.page.on(tap,'#btnMsgSub',function() {
                var msg = $.trim($("#msgInput").val()),
                    bid = $("#bottle").data('bid');
                if (!me.user.id) {
                    $(".leaveMsg .notice").html('登录后才可以回复哦').show();
                    return;
                }

                if(msg){
                    $(".leaveMsg .notice").hide();
                    $.post(me.url.sendMsg ,{
                        method : 'msg',
                        id : me.user.id,
                        bid : bid,
                        msg : msg
                    },function(data) {
                        data = JSON.parse(data);
                        if (data.result) {
                            $("#msgInput").val('');
                            var msgInfo = data.msgInfo;
                            msgInfo.avatar = me.user.avatar;
                            msgInfo.time = Date.now();
                            msgInfo.type = 'me';
                            $("#bottle .msgArea").append( _.template(me.tpls.msg,msgInfo));
                        }
                    })
                }else{
                    $(".leaveMsg .notice").html('请输入信息').show();
                }
            });

        },

        showBottle:function(bottleData) {
            $("#bottle").remove();
            $(".panel").hide();
            var bottle = _.template(this.tpls.bottle, bottleData);
            this.el.page.append(bottle);
        },

        setLoginPanel: function(type) {
            var target, title;
            if (type === 'reg') {
                target = '.regArea';
                title = '注册';
            } else {
                target = '.loginArea';
                title = '登录';
            }
            this.el.loginPanel.find('.inputArea').hide();
            this.el.loginPanel.find('.title').html(title);
            $(target).show();
        },

        showPlayerInfo: function() {
            var me = this;
            if (!this.user.id) return;
            $(".panel").hide();
            $("#playerInfo").remove();
            $.post(this.url.requestInfo,{
                method : 'requestInfo',
                id : me.user.id
            },function(data) {
                data = JSON.parse(data);
                if (data.result) {
                    var obj={
                        avatar : me.user.avatar,
                        name : me.user.name,
                        user : data.user,
                        sys : data.sys
                    }
                }
                me.el.page.append( _.template(me.tpls.playerInfo,obj));
            })
            
        },

        showLoginPanel: function() {
            console.log('dologin');
            $(".panel").hide();
            this.setLoginPanel();
            this.el.loginPanel.show();
        },

        doLogin:function() {
            var uName = $.trim( $("#uName_login").val() );
            var pwd = $.trim( $("#pwd_login").val() );
            var $notice = $("#loginPanel .notice");
            var me = this;
            if (!uName) {
                $notice.html('请填写用户名').show();
                return;
            }
            if (!pwd) {
                $notice.html('请填写密码').show();
                return;
            }
            $notice.hide();
            $.post(this.url.login,{
                method : 'login',
                name : uName,
                pwd : pwd
            },function(data) {
                data = JSON.parse(data);
                if (data.result) {
                    // save sid 
                    me.doLoginSuccess.call(me,data);
                    me.showPlayerInfo.call(me);
                }else{
                    $notice.html(data.errMsg).show();
                }
            });
        },

        doLoginSuccess:function(data) {
            localStorage.setItem('sid',data.sid);
            this.user = data.user;
            this.setCount('g',data.user.count_get);
            this.setCount('t',data.user.count_throw);
            this.el.btnLogin.addClass('logined').find('img').attr('src',data.user.avatar);
        },

        /*
            请求瓶子
            返回格式
            {
                result : 1 ,  // 是否捞到瓶子
                bottle : {
                     bID   // 瓶子id
                     tDate   // throw瓶子的time
                     tID     // throw瓶子的userID
                     tName   // throw到瓶子的name
                     tAvatar  // 头像  
                     msg    
                }
            }
        */
        getBottle: function() {
            var s = Date.now(),
                me = this;
            $.post(this.url.getBottle, {
                method : 'getBottle',
                id: this.user.id || '_GUEST_'
            }, function(data) {
                data = JSON.parse(data);
                // 更新次数
                me.setCount('g',data.count_get);
                var e = Date.now();
                var timeout = me.config.showResult - (e - s);
                timeout = timeout < 0 ? 0 : timeout;
                setTimeout(function() {
                    // hide animate
                    me.el.salvageAnim.removeClass('animate').hide();
                    me.el.btnGet.data('status', '')
                    // show result
                    var resultClass = 's';
                    if (data.result) {
                        // fix data
                        data.bottle.other = data.bottle.role_t;
                        me.newBottle = data.bottle;
                        resultClass = 'b'
                    }
                    me.el.result.attr('class', resultClass).show();
                }, timeout);
            });
        },

        requestList:function() {
            if (!this.user.id) {
                alert('请先登录');
                return;
            }
            var me = this;

            $.post(this.url.requestList, { 
                method :'requestList',
                id : 11//this.user.id 
            }, function(data) {
                data = JSON.parse(data);
                if (data.length) {
                    $("#bottleList").remove();
                    $(".panel").hide();
                    var list = _.template(me.tpls.bottleList ,{list : data});
                    me.el.page.append(list);
                    $("#bottleList").off().on(Util.event.tap,'li',function() {
                        me.requestBottle.call(me,$(this).data('bid'))
                    });
                }
            });
        },

        // 通过id请求瓶子
        requestBottle : function(bid) {
            var me = this;
            if (!bid) return;
            $.post(this.url.requestBottle,{
                method:'requestBottle',
                bid : bid
            },function(data) {
                data = JSON.parse(data);
                if (data.result && me.user.id) {
                    data.bottle.other = me.user.id == data.bottle.role_t.id ? data.bottle.role_g : data.bottle.role_t;
                    console.log(data.bottle);
                    me.showBottle.call(me,data.bottle)
                }
            })
        },
        
        TEST: function() {
            
        }

    }


    var bottleAPP = new app();

});